'use strict'
import {
  app,
  protocol,
  BrowserWindow,
  ipcMain
} from 'electron'
import {
  createProtocol
} from 'vue-cli-plugin-electron-builder/lib'
import installExtension, {
  VUEJS_DEVTOOLS
} from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
// 必须在应用程序准备好之前注册方案
protocol.registerSchemesAsPrivileged([{
  scheme: 'app',
  privileges: {
    secure: true,
    standard: true
  }
}])
async function createWindow() {
  const win = new BrowserWindow({
    minWidth: 550,
    width: 600,
    minHeight: 270,
    maxHeight: 270,
    height: 270,
    frame: false,
    transparent: true,
    title: 'bilibili小工具',
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      // 跨域
      webSecurity: false,
    }
  })
  // 置顶
  ipcMain.on('onTop', () => {
    win.setAlwaysOnTop(true)
  })
  // 取消置顶
  ipcMain.on('!onTop', () => {
    win.setAlwaysOnTop(false)
  })
  // 关闭窗口
  ipcMain.on('closeWindow', () => {
    win.destroy()
  })
  // 最小化
  ipcMain.on('miniWindow', () => {
    win.minimize()
  })
  // 禁止更改窗口大小
  ipcMain.on('FixedWindow', () => {
    win.setResizable(false)
  })
  ipcMain.on('!FixedWindow', () => {
    win.setResizable(true)
  })
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    win.loadURL('app://./index.html')
  }
}
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()
})
//根据开发模式的父进程的请求干净地退出。
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}